import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from MedicineReminder.models import Medicine, ReminderItem
from SecureHelperServer.settings import formatResponseData
from utils.conf import Response
from utils.custom import MyJWTAuthentication


class GetMedicineList(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        获取药品信息
        """
        data = copy.deepcopy(formatResponseData)
        try:
            # 查询出对应时间范围之内的药品信息
            medicines = Medicine.objects.filter(user=request.user)

            # 存入药品
            medicineList = []
            for medicine in medicines:
                medicineObj = {
                    "id": medicine.id,
                    "name": medicine.name,
                    "startDateTimeStamp": medicine.startTimeStamp,
                    "endDateTimeStamp": medicine.endTimeStamp,
                    "dosage": medicine.dosage,
                    "status": medicine.status,
                    "reminderItemList": []
                }

                # 存入对应药品的提醒项
                reminderItemList = ReminderItem.objects.filter(medicine=medicine)
                for reminderItem in reminderItemList:
                    reminderItemObj = {
                        "id": reminderItem.id,
                        "timeStamp": reminderItem.timeStamp,
                    }
                    medicineObj["reminderItemList"].append(reminderItemObj)

                medicineList.append(medicineObj)

            data["data"]["medicineList"] = medicineList
            return Response(data=data, loggerMsg=f"获取药品信息: 成功，uid={request.user.uid}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
